import { Module } from 'vuex'
import { IRootState } from '../type'
import { ILoginState } from './type'
import router from '@/router'
import {
  accountLoginRequest,
  requestUserInfoById,
  requestUserMenusByRoleId
} from '@/service/login/login'
import { mapMenusRoutes } from '@/utils/map-menus'
import { IAccount } from '@/service/login/type'
import localCache from '@/utils/cache'
const loginModule: Module<ILoginState, IRootState> = {
  namespaced: true,
  state() {
    return {
      token: '',
      userInfo: {},
      userMenus: []
    }
  },
  getters: {},
  mutations: {
    changeVal(state, obj: any) {
      Reflect.ownKeys(obj).forEach((key) => {
        Reflect.set(state, key, obj[key])
      })
    },
    changeUserMenus(state, userMenus: any) {
      state.userMenus = userMenus

      // userMenus => routes
      const routes = mapMenusRoutes(userMenus)

      // 将routes => router.main.children

      routes.forEach((route) => {
        router.addRoute('main', route)
      })
    }
  },
  actions: {
    async accountLoginAction({ commit, dispatch }, payload: IAccount) {
      // 实现登录逻辑
      const loginResult = await accountLoginRequest(payload)
      const { id, token } = loginResult.data
      commit('changeVal', { token })
      localCache.setCache('token', token)
      dispatch('getInitialDataAction', null, { root: true })
      // 请求用户信息
      const userInfoResult = await requestUserInfoById(id)
      const userInfo = userInfoResult.data
      commit('changeVal', { userInfo })
      localCache.setCache('userInfo', userInfo)
      // 请求用户菜单
      const userMenusResult = await requestUserMenusByRoleId(userInfo.role.id)
      const userMenus = userMenusResult.data
      commit('changeUserMenus', userMenus)
      localCache.setCache('userMenus', userMenus)
      // 跳到首页
      router.push('/main')
    },
    // 防止刷新页面vuex数据丢失
    loadLocalLogin({ commit }) {
      const token = localCache.getCache('token')
      if (token) {
        commit('changeVal', { token })
      }
      const userInfo = localCache.getCache('userInfo')
      if (userInfo) {
        commit('changeVal', { userInfo })
      }
      const userMenus = localCache.getCache('userMenus')
      if (userMenus) {
        commit('changeUserMenus', userMenus)
      }
    }
  }
}
export default loginModule
